package com.tinyideatech.wechat.controller;

import static com.tinyideatech.common.core.entity.ApiResult.warn;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tinyideatech.common.core.controller.BaseController;
import com.tinyideatech.common.core.entity.ApiResult;
import com.tinyideatech.framework.dto.FTP;
import com.tinyideatech.system.entity.CarModel;
import com.tinyideatech.system.entity.MallGoods;
import com.tinyideatech.system.service.ICarModelService;
import com.tinyideatech.system.service.IMallGoodsService;

@RestController
@RequestMapping("/ws/v2/api")
public class ModelController extends BaseController {
    @Autowired
    private ICarModelService modelService;

    @Autowired
    private IMallGoodsService goodsService;

    @Autowired
    private FTP ftpCatalog;

    @PostMapping("/model/verify")
    public ApiResult verifyModel(@RequestParam String deviceId, @RequestParam Long modelId,
            @RequestParam String status) {
        JSONObject obj = new JSONObject();
        if (status.equals("1")) {
            // 下载成功，标记记录为逻辑删除。
            modelService.remove(new QueryWrapper<CarModel>().eq("device_id", deviceId).eq("model_id", modelId));

            // 查询是否存在尚未下载车模型。
            List<CarModel> modelList = modelService
                    .list(new QueryWrapper<CarModel>().eq("device_id", deviceId).eq("del_flag", 1));
            if (modelList.size() == 0) {
                // 车模型全部下载完成。
                return warn("vehicle list is null");
            } else {
                // 返回首个未下载车模型。
                CarModel model = modelList.get(0);
                obj.put("modelId", model.getModelId());
                String ftpUrl = ftpCatalog.getFullPathMODFtp() + model.getModelUrl();
                obj.put("url", ftpUrl);
                obj.put("md5", model.getMd5());
                return success(obj);
            }
        } else {
            // 强制更新车模型。
            MallGoods mallGood = goodsService.getOne(new QueryWrapper<MallGoods>().eq("url", modelId + ".tar.gz"));

            obj.put("modelId", modelId);
            obj.put("url", ftpCatalog.getFullPathMODFtp() + mallGood.getUrl());
            obj.put("md5", mallGood.getMd5());

            return success(obj);
        }
    }
}
